use serde::{Deserialize, Serialize};
use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;
use tracing::error;
use crate::config::{Config, ConfigType};

#[derive(Serialize,Deserialize,Debug)]
pub enum DataType {
    PROVIDER,
    VISITOR
}

#[derive(Serialize,Deserialize,Debug)]
pub struct Data{
    pub data_type: DataType,
    pub name:String
}

impl Data{
    pub fn from_json(json:&str) -> serde_json::Result<Self> {
        serde_json::from_str(json)
    }

    pub fn to_json(&self) -> serde_json::Result<String>{
        serde_json::to_string(self)
    }
}


pub async fn set_auth(stream:&mut TcpStream,config:&Config){
    let data_type = match config.config_type {
        ConfigType::Provider => DataType::PROVIDER,
        ConfigType::Visitor => DataType::VISITOR
    };
    let data = Data {
        name: config.client.name.to_string(),
        data_type
    };
    match data.to_json() {
        Ok(json) => {
            if let Err(e) = stream.write_i32(json.len() as i32).await{
                error!("{e}")
            }
            if let Err(e) = stream.write_all(json.as_bytes()).await{
                error!("{e}")
            }
            if let Err(e) = stream.flush().await{
                error!("{e}")
            }
        }
        Err(e) => {
            error!("数据转换错误:{e}")
        }
    }
}

